"""
待办事项数据模型

功能说明：
1. 定义待办事项的数据库模型
2. 支持多状态管理（待完成、进行中、已完成）
3. 确保用户数据隔离
"""

from sqlalchemy import Column, Integer, String, Text, DateTime, Enum, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
import enum
from app.database import Base


class TodoStatus(str, enum.Enum):
    """待办事项状态枚举"""
    PENDING = "pending"          # 待完成
    IN_PROGRESS = "in_progress"  # 进行中
    COMPLETED = "completed"      # 已完成


class Todo(Base):
    """待办事项模型"""
    __tablename__ = "todos"

    # 主键
    id = Column(Integer, primary_key=True, index=True, comment="待办事项ID")
    
    # 用户关联
    user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False, comment="用户ID")
    
    # 基本信息
    title = Column(String(50), nullable=False, comment="待办事项标题")
    content = Column(Text, nullable=True, comment="待办事项内容")
    # Store enum VALUE strings in DB (pending/in_progress/completed) for consistency with API
    status = Column(Enum(TodoStatus, values_callable=lambda obj: [e.value for e in obj]), default=TodoStatus.PENDING, nullable=False, comment="待办事项状态")
    
    # 时间字段
    create_time = Column(DateTime(timezone=True), server_default=func.now(), nullable=False, comment="创建时间")
    update_time = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), nullable=True, comment="更新时间")
    
    # 关联关系
    user = relationship("User", back_populates="todos")
    
    def __repr__(self):
        return f"<Todo(id={self.id}, title='{self.title}', status='{self.status}')>"
    
    def to_dict(self):
        """转换为字典格式"""
        return {
            "id": self.id,
            "user_id": self.user_id,
            "title": self.title,
            "content": self.content,
            "status": self.status.value,
            "create_time": self.create_time.isoformat() if self.create_time else None,
            "update_time": self.update_time.isoformat() if self.update_time else None
        }
